﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using System;
using System.CodeDom;
using System.IO;

[assembly: CommandClass(typeof(InsertOlePicture))]

public class InsertOlePicture
{
    [CommandMethod("InsertOlePic")]
    public void InsertOlePic()
    {
        Document doc = Application.DocumentManager.MdiActiveDocument;
        Editor ed = doc.Editor;

        // Prompt for the insertion point
        PromptPointResult ppr = ed.GetPoint("Enter insertion point: ");
        if (ppr.Status != PromptStatus.OK) return;

        Point3d insertionPoint = ppr.Value;

        // Prompt for the file path of the image
        PromptOpenFileOptions opts = new PromptOpenFileOptions("Select an image file");
        opts.Filter = "Image Files|*.bmp;*.jpg;*.jpeg;*.png;*.gif";
        PromptFileNameResult pfnr = ed.GetFileNameForOpen(opts);
        if (pfnr.Status != PromptStatus.OK) return;

        string imagePath = pfnr.StringResult;

        // Check if the file exists
        if (!File.Exists(imagePath))
        {
            ed.WriteMessage("\nFile not found.");
            return;
        }

        // Open the Block table for read
        using (Transaction tr = doc.TransactionManager.StartTransaction())
        {
            BlockTable bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);

            // Open the Block table record Model space for write
            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

            // Create an Ole object
            using (OleObject oleObj = new OleObject())
            {
                oleObj.ClassType = "AcOlePicture";
                oleObj.SourceFileName = imagePath;

                // Insert the Ole object into the block table record
                btr.AppendEntity(oleObj);
                tr.AddNewlyCreatedDBObject(oleObj, true);

                // Set the insertion point and scale
                oleObj.TransformBy(Matrix3d.Displacement(insertionPoint.GetVectorTo(Point3d.Origin)));
                oleObj.ScaleFactors = new Scale3d(1.0, 1.0, 1.0);
            }

            // Save the changes and close the transaction
            tr.Commit();
        }

        ed.WriteMessage("\nOLE Picture inserted successfully.");
    }

    public void InsertOleImageFrame()
    {

    }
}
